package protocol;

import java.util.Vector;

import javax.swing.text.Position;

import msg.Message;
import network.Network;
import time.Clock;
import event.Event;
import event.EventQueue;

/*
 * Created on 2005-3-11
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author Lizzy
 *
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class Node {
	// static Network network;

	int ip;// readable label
	public ID id;// hash code of this node as DHT key
	boolean alive;
	Position position;
	Vector neighbors;// vector of nodes.
	RoutingTable routingTable;

	/*
	 * static void setNetwork(Network net){ network = net; }
	 */
	Node() {
		ip = 0;
		id = null;
		neighbors = new Vector(20);
		alive = false;
	}

	public Node(int ip, Position p) {

		this.ip = ip;
		this.id = new ID(this.hashCode());
		neighbors = new Vector(20);
		position = p;
		alive = false;
	}

	public void join(Node wellKnown) {
		System.out.println(new Integer(Clock.now()).toString() + "::" + id
				+ ": started to join");
		alive = true;
		if (this == wellKnown) {
			EventQueue.getInstance()
					.add(
							new Event(Event.JOINED, Clock.now(), this,
									wellKnown, null));
		} else {
			int timeToJoin = Clock.now() + Network.getInstance().getDelay();
			EventQueue.getInstance().add(
					new Event(Event.JOINED, timeToJoin, this, wellKnown, null));
		}
	}

	public void beJoined(Node newNode) {
		// TODO Auto-generated method stub
		/**
		 * if (i am responsible for node) { let it join. initialize this new
		 * node. mark it as join successed. } else{ nx =
		 * Network.find_next_hop(this,node) eventQueue.addEvent("beJoined",args) }
		 */
		System.out.println(new Integer(Clock.now()).toString() + "::"
				+ newNode.id + " has joined from " + id);
	}

	Position getPosition() {
		return position;
	}

	void addNeighbor(Node newNeighbor) {
		neighbors.add(newNeighbor);
	}

	void sendMessage(Node des, Message msg) {
		Network.getInstance().send(this, des, msg);
	}

	boolean isAlive() {
		return alive;
	}
}
